package com.example.springbootdemo.handler;

import com.alibaba.fastjson.JSON;
import com.example.springbootdemo.config.JwtConfig;
import com.example.springbootdemo.config.ThreadConfig;
import com.example.springbootdemo.mapper.UserInfoMapper;
import com.example.springbootdemo.mapper.UserMapper;
import com.example.springbootdemo.vo.ResultVo;
import com.example.springbootdemo.vo.UserInfoVo;
import com.example.springbootdemo.vo.UserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserHandler {
    private static final Logger LOGGER = LoggerFactory.getLogger(UserHandler.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private RestTemplate restTemplate;

    @Value("${gitee.client_id}")
    private String clientId;

    @Value("${gitee.client_secret}")
    private String clientSecret;
    @Value("${gitee.redirect_url}")
    private String redirectURL;

    public ResultVo login(UserVo user) {

        UserVo login = userMapper.login(user);
        if (login == null) {
            // 用户不存在
            return ResultVo.error("用户不存在");
        }
        String token = JwtConfig.generateToken(user.getUserName());
        login.setToken(token);
        return ResultVo.success(login);
    }

    public ResultVo getList(Map<String, Object> inputMap) {
        int size = inputMap.get("pageSize") == null ? 20 : Integer.parseInt(String.valueOf(inputMap.get("pageSize"))); // 显示条数
        int currentPage = inputMap.get("currentPage") == null ? 0 : (Integer.parseInt(String.valueOf(inputMap.get("currentPage"))) - 1) * size; // 当前页
        inputMap.put("currentPage", currentPage);
        inputMap.put("pageSize", size);
        if (inputMap.get("username") != null && !"".equals(inputMap.get("username").toString().trim())) {
            String userName = "%" + inputMap.get("username") + "%";
            inputMap.put("username", userName);
        }
        if (inputMap.get("age") != null && !"".equals(inputMap.get("age").toString().trim())) {
            String age = String.valueOf(inputMap.get("age"));
            String[] split = age.split(",");
            inputMap.put("between", split[0]);
            inputMap.put("and", split[1]);
        }

        int count = userMapper.getCount(inputMap);
        List<UserVo> dataList = userMapper.getList(inputMap);
        Map<String, Object> outMap = new HashMap<>();
        outMap.put("count", count);
        outMap.put("data", dataList);
        return ResultVo.success(outMap);
    }

    /**
     * 用户第三方登录接口
     *
     * @param code
     * @param writer
     * @return
     */
    public String thirdPartyLogins(String code, PrintWriter writer) {
        String access_token = getAccessToken(code);
        if (access_token == null) {
            writer.println("getAccessToken error");
            return null;
        }
        Map<String, Object> body = getUserInfo(access_token);
        if (body == null) {
            writer.println("thirdPartyLogins getInfo fial");
            return null;
        }
        boolean offer = ThreadConfig.BLOCKING_QUEUE.offer(body);
        if (!offer) {
            LOGGER.error("blockingQueue.offer error!");
            LOGGER.error(JSON.toJSONString(body));
        }
        return JwtConfig.generateToken(String.valueOf(body.get("login")));
    }

    /**
     * 查询用户是否已经注册
     *
     * @return 用户是否已经注册
     */


    private Map<String, Object> getUserInfo(String accessToken) {
        // 通过该地址能够获取到用户信息
        String url = "https://gitee.com/api/v5/user?access_token=" + accessToken;
        HttpEntity<String> httpEntity = getStringHttpEntity(accessToken);
        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
        if (exchange.getStatusCode() != HttpStatus.OK) {
            return null;
        }
        return JSON.parseObject(exchange.getBody(), Map.class);
    }

    /**
     * 获取Gitee的令牌
     *
     * @return 令牌
     */
    private String getAccessToken(String code) {
        Map<String, Object> inputMap = new HashMap<String, Object>() {
            {
                put("grant_type", "authorization_code");
                put("client_id", clientId);
                put("client_secret", clientSecret);
                put("code", code);
                put("redirect_uri", redirectURL);
            }
        };
        HttpEntity<String> httpEntity = getStringHttpEntity(inputMap);
        String url = "https://gitee.com/oauth/token";
        //ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
        ResponseEntity<String> exchange = restTemplate.postForEntity(url, httpEntity, String.class);
        if (exchange.getStatusCode() != HttpStatus.OK) {
            return null;
        }
        Map map = JSON.parseObject(exchange.getBody(), Map.class);
        if (map == null) {
            return null;
        }
        return String.valueOf(map.get("access_token"));
    }

    private HttpEntity<String> getStringHttpEntity(Object inputMap) {
        MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(type);
        headers.add("Accept", MediaType.APPLICATION_JSON.toString());

        return new HttpEntity<>(JSON.toJSONString(inputMap), headers);
    }

    public UserInfoVo getInfo(Map<String, Object> inputMap) {
        return userInfoMapper.getUserInfo(inputMap);
    }
}
